package com.apimanage.common.health;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;

import java.util.Properties;

/**
 * Nacos连接健康检查器
 * 检查Nacos服务的连接状态
 *
 * @author API管理平台
 */
@Component
public class NacosHealthChecker implements HealthChecker {
    
    private static final Logger logger = LoggerFactory.getLogger(NacosHealthChecker.class);
    private static final String CHECKER_NAME = "Nacos服务连接检查";
    
    @Value("${spring.cloud.nacos.discovery.server-addr:127.0.0.1:8848}")
    private String serverAddr;
    
    @Value("${spring.cloud.nacos.discovery.namespace:}")
    private String namespace;
    
    @Value("${spring.cloud.nacos.discovery.username:nacos}")
    private String username;
    
    @Value("${spring.cloud.nacos.discovery.password:nacos}")
    private String password;
    
    @Override
    public HealthCheckResult check() {
        HealthCheckResult result = new HealthCheckResult(true, CHECKER_NAME);
        
        try {
            // 创建Nacos连接属性
            Properties properties = new Properties();
            properties.setProperty("serverAddr", serverAddr);
            if (namespace != null && !namespace.isEmpty()) {
                properties.setProperty("namespace", namespace);
            }
            if (username != null && !username.isEmpty()) {
                properties.setProperty("username", username);
            }
            if (password != null && !password.isEmpty()) {
                properties.setProperty("password", password);
            }
            
            // 创建NamingService实例
            NamingService namingService = NacosFactory.createNamingService(properties);
            
            if (namingService == null) {
                result.setHealthy(false);
                result.addMessage("Nacos命名服务实例为null");
                return result;
            }
            
            // 执行心跳测试或获取服务列表测试连接
            namingService.getServicesOfServer(0, 1);
            
            // 获取连接信息
            result.addMessage("Nacos连接成功");
            result.addMessage("服务器地址: " + serverAddr);
            result.addMessage("命名空间: " + (namespace.isEmpty() ? "public" : namespace));
            
        } catch (NacosException e) {
            result.setHealthy(false);
            result.addMessage("Nacos连接失败: " + e.getMessage());
            logger.error("Nacos连接检查失败", e);
        } catch (Exception e) {
            result.setHealthy(false);
            result.addMessage("Nacos健康检查异常: " + e.getMessage());
            logger.error("Nacos健康检查异常", e);
        }
        
        return result;
    }
    
    @Override
    public String getName() {
        return CHECKER_NAME;
    }
}